package oss

import (
	"gitee.com/slclub/aliyun-oss/conf"
	"gitee.com/slclub/aliyun-oss/logq"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

var client *oss.Client

func Client() *oss.Client {
	if client == nil {
		endpoint := "https://oss-" + conf.Config.OSS.RegionId + ".aliyuncs.com"
		client, _ = oss.New(endpoint, conf.Config.OSS.AccessKeyId, conf.Config.OSS.AccessKeySecret)
		return client
	}
	return client
}

func Bucket(bucket_name string) *oss.Bucket {
	bucket, err := Client().Bucket(bucket_name)
	if err != nil {
		logq.Warn("[OSS][BUCKET][GET]ERR", bucket_name)
	}
	return bucket
}

// 100 一页
func GetObjectV2(bucket_name string, prefix_str string) ([]string, string) {
	// 分页列举包含指定前缀的文件。每页列举80个。
	prefix := oss.Prefix(prefix_str)
	marker := oss.Marker("")
	bucket := Bucket(bucket_name)
	result := make([]string, 1)
	endpoint := "https://" + bucket_name + ".oss-" + conf.Config.OSS.RegionId + ".aliyuncs.com/"
	marker_rtn := ""
	for {
		lor, err := bucket.ListObjects(marker, prefix)
		if err != nil {
			logq.Warn("Error:", err)
		}
		for _, object := range lor.Objects {
			//fmt.Println(object.Key, object.Type, object.Size, object.ETag, object.LastModified, object.StorageClass)
			result = append(result, endpoint+object.Key)
		}
		if lor.IsTruncated {
			prefix = oss.Prefix(lor.Prefix)
			marker = oss.Marker(lor.NextMarker)
			marker_rtn = lor.NextMarker
			break
		} else {
			marker_rtn = ""
			break
		}
	}
	return result, marker_rtn
}
